<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, unref, nextTick, watch, reactive } from 'vue'
import {
  ElTree,
  ElInput,
  ElDivider,
  ElTag,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElForm,
  ElRow,
  ElCol,
  ElFormItem
} from 'element-plus'
import { getDepartmentApi, userDeptPageApi } from '@/api/department'
import type { DepartmentItem, UserResponse } from '@/api/department/types'
import { Refresh, Search } from '@element-plus/icons-vue'
import Edit from './components/Edit.vue'

const { t } = useI18n()

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
const departmentList = ref<DepartmentItem[]>([])
const treeLoading = ref(false)
const loadDeptList = async () => {
  treeLoading.value = true
  const res = await getDepartmentApi()
  departmentList.value = res.data
  currentNodeKey.value = (res.data[0] && res.data[0]?.child && res.data[0].child[0].id) || ''
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
  treeLoading.value = false
}
loadDeptList()

const form = reactive({
  name: '',
  status: '',
  roleId: ''
})

const userLoading = ref(false)
const userList = ref<UserResponse[]>([])
const pagination = ref({
  pageSizes: [10, 20, 50, 100],
  total: 0,
  pageSize: 20,
  currentPage: 1
})
const loadDeptUserList = async (data) => {
  userLoading.value = true
  const res = await userDeptPageApi(data)
  userList.value = res.data.records
  pagination.value.total = res.data.total - 0
  userLoading.value = false
}
loadDeptUserList({
  pageNum: pagination.value.currentPage,
  pageSize: pagination.value.pageSize
})
const pageChange = (data) => {
  loadDeptUserList({
    pageNum: pagination.value.currentPage,
    pageSize: pagination.value.pageSize,
    ...data
  })
}
const resetAndLoadDeptUserList = (data = {}) => {
  pagination.value.currentPage = 1
  pageChange(data)
}

const currentDepartment = ref('')

watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const refresh = () => {
  loadDeptList()
  form.name = ''
  form.status = ''
  form.roleId = ''
  resetAndLoadDeptUserList(form)
}

const search = () => {
  resetAndLoadDeptUserList(form)
}

const filterNode = (value: string, data: DepartmentItem) => {
  if (!value) return true
  return data.name.includes(value)
}

const nodeClick = (data) => {
  // 点击节点的时候，只查询这个节点及这个节点的下级数据
  resetAndLoadDeptUserList({
    deptId: data.id
  })
}

const handleEdit = (index, row) => {
  console.log(index, row)
  const edit = unref(editRef)
  edit?.onUpdate(true, row)
}

const handleDelete = (row) => {
  console.log(row)
}

const editRef = ref<ComponentRef<typeof Edit>>()
const onAdd = () => {
  const edit = unref(editRef)
  edit?.onAdd(true)
}

const onClose = (p1, p2) => {
  console.log('子窗口回调', p1, p2)
  resetAndLoadDeptUserList()
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-30%">
      <div class="flex justify-center items-center">
        <div class="flex-1">{{ t('userDemo.departmentList') }}</div>
        <ElInput
          v-model="currentDepartment"
          class="flex-[2]"
          :placeholder="t('userDemo.searchDepartment')"
          :prefix-icon="Search"
          clearable
        />
      </div>
      <ElDivider />
      <ElTree
        v-loading="treeLoading"
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'name',
          children: 'child'
        }"
        :filter-node-method="filterNode"
        @node-click="nodeClick"
      >
        <template #default="{ data }">
          <div :title="data.name" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.name }}
            <ElTag v-if="data.status != 1" type="info">禁用</ElTag>
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-10px">
      <el-form ref="formRef" :model="form" label-width="auto" label-position="top">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="用户名" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="昵称">
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col>
            <el-button size="small" :icon="Search" @click="search">查询</el-button>
            <el-button size="small" :icon="Refresh" @click="refresh">重置</el-button>
            <el-button size="small" :icon="Refresh" @click="onAdd">新增</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        v-loading="userLoading"
        :data="userList"
        :border="true"
        stripe
        style="width: 100%"
        class="mt-10px"
      >
        <el-table-column type="index" width="45" />
        <el-table-column type="selection" width="40" />
        <el-table-column prop="name" label="用户名" width="100" />
        <el-table-column prop="nickName" label="昵称" width="100" />
        <el-table-column prop="phone" label="手机" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.status != 1" type="info">禁用</el-tag>
            <el-tag v-else type="success">启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="部门" width="150" />
        <el-table-column prop="roleName" label="角色" width="100" />
        <el-table-column label="Operations" width="140" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        class="mt-10px"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-sizes="pagination.pageSizes"
        v-model:page-size="pagination.pageSize"
        v-model:current-page="pagination.currentPage"
        @change="pageChange"
      />
    </ContentWrap>

    <Edit ref="editRef" @onClose="onClose" />
  </div>
</template>
